<?php
namespace app\manage\controller;
use think\facade\Db;
use think\Exception;

class Index extends Base
{
    //检查是否绑定手机号, 并验证token时间, 如果快过期了可以更新
    public function refreshToken() {
        try {
            $time = time();
            $new_token = $this->userinfo['token'];
            if((time() - $this->userinfo['create_time']) > config('app.token_expires_time')/2) {
                $new_token = md5($this->userinfo['token'] . $time);
                $update = [
                    'create_time' => $time,
                    'token' => $new_token
                ];
                Db::table('mp_admin_token')->where('token','=',$this->userinfo['token'])->update($update);
            }
        } catch (\Exception $e) {
            mylog($this->cmd,$e->getMessage());
            return ajax($e->getMessage(),-1);
        }
        $ret = [
            'token' => $new_token
        ];
        return ajax($ret);

    }

    public function getMyMenu() {
        if($this->userinfo['admin_id'] === 1) {
            $whereRoute = [
                ['del','=',0]
            ];
            $routeList = Db::table('mp_menu')->where($whereRoute)->field('id,title,path,icon,pid')->order(['sort'=>'DESC','id'=>'ASC'])->select();
            $new_arr = [];
            foreach ($routeList as $route) {
                if($route['pid'] === 0) {
                    $subs = [];
                    foreach ($routeList as $v) {
                        if($route['id'] == $v['pid']) {
                            $subs[] = $v;
                        }
                    }
                    $route['subs'] = $subs;
                    $new_arr[] = $route;
                }
            }
        }else {
            $role = Db::table('mp_auth_role')->where('id','=',$this->userinfo['role'])->find();
            if(!$role) {
                $new_arr = [];
            }else {
                $new_arr = json_decode($role['route_content'],true);
            }
        }
        return ajax($new_arr);
    }

    public function userInfo() {
        $login = input('post.login');
        try {
            $where = [
                ['id','=',$this->userinfo['admin_id']]
            ];
            $exist = Db::table('mp_admin')->where($where)->find();
            if($login === 'login') {
                $location = $this->getLocation();
                if($exist['last_login_province'] && $location['province'] !== $exist['last_login_province']) {
                    $sendData = [
                        'plat' => $_SERVER['HTTP_HOST'],
                        'username' => $exist['username'],
                        'province' => $location['province'],
                        'email' => $exist['email'],
                    ];
                    $this->asyn_email_send($sendData);
                }
                $update_data = [
                    'ip' => $location['ip'],
                    'province' => $location['province']
                ];
                Db::table('mp_admin_token')->where('token','=',$this->userinfo['token'])->update($update_data);
                Db::table('mp_admin')->where($where)->update(['last_login_province'=>$location['province']]);
                $log_data = [
                    'type' => 0,
                    'admin_id' => $exist['id'],
                    'create_time' => time(),
                    'ip' => $location['ip'],
                    'region' => $location['province'],
                    'login_type' => $this->userinfo['login_type']
                ];
                Db::table('mp_syslog')->insert($log_data);
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $exist['token'] = $this->userinfo['token'];
        return ajax($exist);
    }

    public function avatarMod() {
        $tmp_image = input('post.pic','');
        try {
            if(!$tmp_image) {
                return ajax('请上传图片',3);
            }
            $where = [
                ['id','=',$this->userinfo['admin_id']]
            ];
            if(!file_exists($tmp_image)) {
                return ajax('图片已失效请重新上传',4);
            }
            $image_move = move_file_to_directory($tmp_image,'upload/avatar/');
            if($image_move['code'] == 0) {
                $post['avatar'] = $image_move['path'];
            }else {
                return ajax('转移图片失败',72);
            }
            Db::table('mp_admin')->where($where)->update($post);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax($post);
    }

    public function userMod() {
        $password = input('post.password','');
        $newpassword = input('post.newpassword','');
        $post['realname'] = input('post.realname','');
        $post['desc'] = input('post.desc','');
        try {
            if($newpassword) {
                if(!$password) {
                    return ajax('password',-2);
                }
                $wherePass = [
                    ['id','=',$this->userinfo['admin_id']],
                    ['password','=',md5($password . config('app.login_key'))]
                ];
                $exist = Db::table('mp_admin')->where($wherePass)->find();
                if(!$exist) {
                    return ajax('密码错误',52);
                }
                $post['password'] = md5($newpassword . config('app.login_key'));
            }
            $where = [
                ['id','=',$this->userinfo['admin_id']]
            ];
            Db::table('mp_admin')->where($where)->update($post);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }



    //暂时没用到
    public function uploadImage() {
        $accessKeyId = config('accessKeyId');
        $accessKeySecret = config('accessKeySecret');
        $endpoint = "https://oss-cn-beijing.aliyuncs.com";
        $bucket = config('ali_bucket');

        if (empty($_FILES)) {
            return $this->ajax('请上传图片', 3);
        }
        if (count($_FILES) > 1) {
            return $this->ajax('最多上传一张图片', 7);
        }
        $upload = $_FILES[array_keys($_FILES)[0]];
        if($upload['error'] === 0) {
            $allowType = [ 'image/jpeg', 'image/bmp' ,'image/gif' ,'image/png','image/jpg','image/pjpeg','image/x-png','image/webp'];
            if(!in_array($upload['type'],$allowType)) {
                return $this->ajax('不支持的图片格式' . $upload['type'],4);
            }
            if($upload['size'] > 1024*1024) {
                return $this->ajax('图片大小不能超过1M',6);
            }
            $local_file = $upload['tmp_name'];
            $content = file_get_contents($local_file);
            $object = 'wangeditor/' . create_unique_number('') . randname(6) . '.' . substr('image/jpeg',6);
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->putObject($bucket, $object, $content);
            } catch (OssException $e) {
                return $this->ajax($e->getMessage(),-1);
            }
            $data = [
                [
                    'url' => config('editor_prefix') . $object,
                    'alt' => '',
                    'href' => ''
                ]
            ];
            return $this->ajax($data,0);
        }else {
            return $this->ajax('上传失败',-1);
        }
    }

    private function ajax($data = [], $code = 1, $message = '', $header = [])
    {
        $ret = [
            'message' => config('code.' . $code),
            'errno' => $code,
            'data' => $data,
        ];
        if($message) {
            $ret['message'] = $message;
        }
        if (config('app_debug')) {
            $ret['cmd'] = request()->controller() . '/' . request()->action();
        }
        $header['X-Powered-By'] = config('app_name');
        $httpCode = 200;
        $header['origin'] = json_encode(request()->subDomain());
        header('Access-Control-Allow-Origin: *');
        return json()->data($ret)->code($httpCode)->header($header);
    }

    //高德地图获取地理位置
    private function getLocation() {
        $ip = $this->getip();
        $parameters = [
            'key' => '3a69bef99855dc5d7e80809e59111a4b',
            'ip' => $ip,
        ];
        $url = 'https://restapi.amap.com/v3/ip?'.http_build_query($parameters);
        $res = curl_get_data($url);
        $res = json_decode($res,true);
        $res['ip'] = $ip;
        return $res;
    }

    private function getip() {
        $unknown = 'unknown';
        if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        /*
        处理多层代理的情况
        或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
        */
        if (false !== strpos($ip, ',')) {
            $ip_arr = explode(',', $ip);
            $ip = reset($ip_arr);
        }
        return $ip;
    }

    private function asyn_email_send($data) {
        $host = $_SERVER['HTTP_HOST'];
        $param = http_build_query($data);
        $fp = @fsockopen('ssl://' . $host, 443, $errno, $errstr, 20);
        if (!$fp){
            mylog($this->cmd,'error fsockopen','fsockopen.log');
        }else{
            stream_set_blocking($fp,0);
            $http = "GET /manage/email/accountWarning?".$param." HTTP/1.1\r\n";
            $http .= "Host: ". $host ."\r\n";
            $http .= "Connection: Close\r\n\r\n";
            fwrite($fp,$http);
            usleep(1000);
            fclose($fp);
        }
    }


}
